//
//  CZplacehoderTextView.swift
//  SinaBlog
//
//  Created by 李超 on 16/3/30.
//  Copyright © 2016年 lichao. All rights reserved.
//

import UIKit

class CZplacehoderTextView: UITextView {
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        prepareUI()
        self.font = UIFont.systemFontOfSize(18)
        
    }
    //自定义占位文字的属性
    var placeholderString:String?{
        didSet{
         self.placeholderLable.text = placeholderString
            //先设置文字，在来自适应
            placeholderLable.sizeToFit()
        }
    }
    //重写设置字体的属性
    override var font: UIFont?{
        didSet{
            placeholderLable.font = font
        }
        
    }
    //添加控件以及做相关约束
    func prepareUI(){
        //添加占位lable
        addSubview(placeholderLable)
        placeholderLable.translatesAutoresizingMaskIntoConstraints = false
        self.addConstraint(NSLayoutConstraint(item: placeholderLable, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 8.0))
        self.addConstraint(NSLayoutConstraint(item: placeholderLable, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 5.0))
        //注册通知，不适用代理，代理留着外面控制器使用
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChange:", name: UITextViewTextDidChangeNotification, object: self)
    
    }
    func textViewDidChange(textView: UITextView) {
        //如果有输入值，则将占位lable隐藏
        self.placeholderLable.hidden = hasText()
    }
    //注销通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //懒加载占位lable
    private lazy var placeholderLable:UILabel = {
        let lable = UILabel()
        lable.textColor = UIColor.lightGrayColor()
        lable.font = UIFont.systemFontOfSize(18)
        return lable
    }()
    
}

